package com.ybkj.o2o.sales.exceptions;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by shine on 15/8/26.
 */
public class SalesExceptionHandler implements HandlerExceptionResolver {

  private static final Logger logger = LoggerFactory.getLogger(SalesExceptionHandler.class);

  private View view;

  public void setView(View view) {
    this.view = view;
  }

  @Override
  public ModelAndView resolveException(HttpServletRequest httpServletRequest,
      HttpServletResponse httpServletResponse, Object object, Exception ex) {

    ModelAndView mv = new ModelAndView();
    ex.printStackTrace();
    logger.error("resolveException:{}", ex.getMessage());

    if (ex instanceof IllegalArgumentException) {

      String message = ex.getMessage();
      mv.getModel().put("code", 101);
      mv.getModel().put("message", message);
      mv.setView(this.view);
      httpServletResponse.setStatus(HttpStatus.UNPROCESSABLE_ENTITY.value());

      return mv;
    }


    return null;
  }
}
